package alipay;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.StringReader;


/**
 * There is a data.txt file, which content is 0. 10 Thread is running to increase the
 * content one, Meanwhile 10 threads are running to read the content.
 * @author Jun
 *
 */
public class ThreadTest {
	
	protected RandomAccessFile raf;
	
	class ReadThread extends Thread{
		
		public ReadThread(String name){
			super(name);
		}
		
		public void run(){
			
			try {
				sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			synchronized (raf) {
				try {
					
					raf.seek(0);
					int i = raf.readInt();
					i++;
					raf.seek(0);
					raf.writeInt(i);
					raf.notifyAll();
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	}
	
	class WriteThread extends Thread{
		
		public WriteThread(String name){
			super(name);
		}
		
		public void run(){
			
			try {
				sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			synchronized (raf) {
				
				try {
					raf.wait();
					raf.seek(0);
					int i = raf.readInt();
					System.out.println("Thread "+ this.getId()+ "num :" +i);
					
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
		}
	}

	public static void main(String[] args) throws IOException{
		
		String file = "E:\\data.txt";
		ThreadTest test = new ThreadTest();
		test.raf = new RandomAccessFile(file, "rw");
		
		
	}
	
	public static void readfile(String filepath) throws IOException{
		
		FileReader fr = null;
		BufferedReader br = null;
		
		try {
			 fr = new FileReader(filepath);
			 br = new BufferedReader(fr);
			String cont = br.readLine();
		}
		finally{			
			if(br != null)
				br.close();			
		}		
	}
	
	public static void RamdomFile(String filepath) throws IOException{
		
		RandomAccessFile raf = new RandomAccessFile(filepath, "rw");
		
		int i = raf.readInt();
		i++;
		raf.seek(0);
		raf.write(i);
		raf.close();
	}
	
}
